package com.example.basic.exception;

import com.example.basic.core.result.Result;
import com.example.basic.core.result.ResultGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class ExceptionAdvice {

    private final Logger logger = LoggerFactory.getLogger(ExceptionAdvice.class);


    @ExceptionHandler(ServiceException.class)
    @ResponseBody
    public Result BizExceptionHandler(ServiceException e) {
        logger.error("全局业务异常：",e);
        return ResultGenerator.genFailResult(e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public Result methodArgumentNotValidException(MethodArgumentNotValidException e) {
        String defaultMessage = e.getBindingResult().getFieldError().getDefaultMessage();
        return ResultGenerator.genFailResult(defaultMessage);
    }

    @ExceptionHandler(Exception.class)
    public Result handleAllExceptions(Exception ex) {
        logger.error("全局业务异常：",ex);
        return ResultGenerator.genFailResult(ex.getMessage());
    }
}

